const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const router = express.Router()

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  const { host, port } = nuxt.options.server

  // Build only in dev mode
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  router.post('/api/login', (req, res) => {
    console.log('server')
    console.log(req.body)

    async function login () {
      console.log('enter login')
      console.log(`server中的${req.body}`)
      const { data } = await axiosServer.post('http://192.168.1.24:8080/bm/opera/login', req.body)
      console.log(`axios返回的数据可能没有${data},看见了没？`)
      return data
    }

    login().then(function (data) {
      // 把token存储到cookie中
      const { token } = data
      if (token) {
        res.cookie('token', token, {
          maxAge: 60000 * 60 * 24
        })
      }
      // 原封不动返回
      return res.json(data)
    })
  })

  app.use(router)

  // Listen the server
  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}
start()
